package com.leyou.controller;

import com.leyou.pojo.User;
import com.leyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户数据的校验
     *
     * @param data
     * @param type
     * @return
     */

    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data,
                                                 @PathVariable("type") Integer type) {
        Boolean bool = this.userService.checkUserData(data, type);
        if (bool != null) {
            return ResponseEntity.status(HttpStatus.OK).body(bool);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户的注册,发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendVerifierCode(@RequestParam("phone") String phone) {
        this.userService.sendVerifierCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户的注册
     *
     * @param user 前台发送的数据,用user对象接收
     * @param code 用户输入的验证码,需要和Redis中的验证码进行比对.
     * @return
     */

    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) {
        Boolean bool = this.userService.register(user, code);
        if (null != bool || bool) {
            //判断是否是空,然后是不是true,进到里面说明组成成功
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    /**
     * 用户的登录(鉴权中心会调用这个方法进行用户的查询)
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<User> queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        User user = this.userService.queryUser(username, password);
        if (user != null) {
            return ResponseEntity.status(HttpStatus.OK).body(user);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
